package com.tanhua.dubbo.server.service.impl;



import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.service.TimeLineService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineServiceImpl implements TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async   //异步执行 ，原理:底层开一个线程去执行该方法
    @Override
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {


        try {
            //查询好友关系表，返回有好友时，写入timeLine对象，无好友时，不用写入timeLine对象，直接返回
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> users = this.mongoTemplate.find(query, Users.class);
            if (CollUtil.isEmpty(users)){
                //无好友，直接返回成功
                return CompletableFuture.completedFuture("ok");
            }
            //填入时间线列表信息
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setUserId(userId);
            timeLine.setPublishId(publishId);
            timeLine.setDate(System.currentTimeMillis());
            //保存至MongoDB中
            this.mongoTemplate.save(timeLine, "quanzi_time_line_" + userId);
        } catch (Exception e) {
            log.error("写入好友时间线表失败，userId = "+ userId + "publishId = " + publishId, e);
            //TODO 事务回滚问题
            return CompletableFuture.completedFuture("error");
        }

        return CompletableFuture.completedFuture("ok");
    }
}
